package com.uubx.exception;


import com.uubx.result.ResultUtils;
import com.uubx.utils.JsonUtils;
import com.uubx.utils.ResponseUtils;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author wyy
 * @Date 2020/12/8 21:55
 * @Version 1.0
 */
public class MyExceptionHandlerResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) {

        String msg="";
        Integer code=null;

        //判断是否是预期异常
        if (exception instanceof CustomerException){

            //向下转型
            CustomerException customerException= (CustomerException) exception;
            msg=customerException.getMessageCode().getMessage();
            code=customerException.getMessageCode().getCode();

        }else {
            exception.printStackTrace();
            msg="对不起,系统开小差了!";
            code=50000;
        }

        //向客户端作出反馈
        ResponseUtils.responseJson(response, JsonUtils.objectToJson(ResultUtils.buildFail(code,msg)));

        ModelAndView modelAndView=new ModelAndView();
        return modelAndView;

    }
}
